package cn.edu.flink.scala.tutorial.window

import cn.edu.flink.scala.tutorial.source.{ClickSource, Event}
import org.apache.flink.api.common.functions.AggregateFunction
import org.apache.flink.streaming.api.scala._
import org.apache.flink.streaming.api.windowing.assigners.SlidingEventTimeWindows
import org.apache.flink.streaming.api.windowing.time.Time

object AggregateFunctionTest {
  def main(args: Array[String]): Unit = {
    val env = StreamExecutionEnvironment.createLocalEnvironmentWithWebUI()
    env.setParallelism(1)

    val eventDS = env.addSource(new ClickSource)
      .assignAscendingTimestamps(_.timestamp)  // WatermarkStrategy.forMonotonousTimestamps() 的替代

    eventDS
      .keyBy(event => "key")
      .window(SlidingEventTimeWindows.of(Time.seconds(10), Time.seconds(2)))
      .aggregate(new Pv ())
      .print()

    env.execute("AggregateFunctionTest")
  }

  // 实现自定义聚合函数，用一个二元组(Long，Set)来表示中间聚合的(pv, uv)状态
  class Pv extends AggregateFunction[Event, Long, Long] {
    override def createAccumulator(): Long = 0L

    override def add(value: Event, accumulator: Long): Long = accumulator + 1

    override def getResult(accumulator: Long): Long = accumulator

    override def merge(a: Long, b: Long): Long = ???
  }
}
